package api

import (
	"api/config"
	"api/internal/api/request"
	"api/internal/api/response"
	"api/internal/handler"
	"common/consulinit"
	pb "exam_srv/proto"
	"flag"
	"github.com/gin-gonic/gin"
	"strconv"
)

var (
	examAddress = config.ServerConfigs.ExamSrv.Host + ":" + strconv.Itoa(config.ServerConfigs.ExamSrv.Port)
	examServer  = flag.String(config.ServerConfigs.ExamSrv.Name, examAddress, "The server address")
	examSrv     = handler.NewClient().ExamServer(examServer)
)

func RegisterExamService() {
	consulinit.NewConsulClient("117.27.231.112", 8500).RegisterConsul(config.ServerConfigs.ExamSrv.Name, []string{"server"},
		config.ServerConfigs.ExamSrv.Port, config.ServerConfigs.ExamSrv.Host)
}

func CreateExam(c *gin.Context) {
	RegisterExamService()
	var json *request.CreateExam
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	value, _ := c.Get("userId")
	s, _ := strconv.Atoi(value.(string))
	exam, err := examSrv.CreateExam(c, &pb.CreateExamRequest{
		UserId:  int64(s),
		PaperId: int64(json.PaperId),
		UserIds: json.UserIds,
		Time:    int64(json.Time),
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "考试创建成功", exam)
}

func ListExam(c *gin.Context) {
	RegisterExamService()
	exam, err := examSrv.ListExam(c, &pb.ListExamRequest{})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "考试展示成功", exam)
}

func FindExam(c *gin.Context) {
	RegisterExamService()
	var json *request.FindExam
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	exam, err := examSrv.FindExam(c, &pb.FindExamRequest{ExamId: int64(json.ExamId)})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "考试详情展示成功", exam)
}

func ExamBegin(c *gin.Context) {
	RegisterExamService()
	var json *request.ExamBegin
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	value, _ := c.Get("userId")
	s, _ := strconv.Atoi(value.(string))
	begin, err := examSrv.ExamBegin(c, &pb.ExamBeginRequest{
		ExamId: int64(json.ExamId),
		UserId: int64(s),
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "考试参加成功", begin)
}

func ExamRank(c *gin.Context) {
	RegisterExamService()
	var json *request.ExamBegin
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	rank, err := examSrv.ExamRank(c, &pb.ExamRankRequest{ExamId: int64(json.ExamId)})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "排行榜返回成功", rank)
}
